package com.example.rabbitmqspringboot.config;/**
 * @program: rabbitmqSpringBoot
 * @author: xlk
 * @create: 2024-04-03 14:33
 */

import com.rabbitmq.client.ConfirmCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

/**
 @auther teacher
 @date 2024/4/3
 @project rabbitmqSpringBoot
 */
@Slf4j
@Component
public class MyConfirmCallback implements RabbitTemplate.ConfirmCallback ,RabbitTemplate.ReturnsCallback{
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostConstruct
    public void init(){
      //注入
      rabbitTemplate.setConfirmCallback(this);
    }
    @PostConstruct
    public void innit(){
        //注入
        rabbitTemplate.setReturnsCallback(this);
    }




  /**
   * 交换机确认回调的方法

   * &#064;param:  * @param correlationData 保存回调消息的ID及相关信息
  * @param ack 交换机是否接收到消息 true是接收到
  * @param cause 失败的原因，成功则为null
  */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
      String id = correlationData.getId()==null?"":correlationData.getId();

      if (ack){
        log.info("交换机接收到了消息,id为{}",id);
      }else {
        log.info("交换机没有收到消息，原因为:{},id为{}",cause,id);

      }


    }


    @Override
    public void returnedMessage(ReturnedMessage returned) {
        byte[] body = returned.getMessage().getBody();
        String message=new String(body);

        String exchange = returned.getExchange();
        String routingKey = returned.getRoutingKey();
        String replyText = returned.getReplyText();
        log.error("消息内容：{}，被交换机：{}退回，退回原因：{}，路由：{}", message, exchange, replyText, routingKey);


    }
}
